import React, { useEffect } from 'react'
import { Form, Input, Button, Result } from 'antd'

import Layout from '../components/layout'
import { SIGNIN, SigninPayload } from '../store/actions/auth'
import { useDispatch, useSelector } from 'react-redux'
import { AppState } from '../store/reducers'
import { AuthState } from '../store/reducers/auth'
import { Redirect } from 'react-router-dom'
import { isAuth } from '../utils/auth'
import { Auth } from '../store/models/auth'

const Signin = () => {
  const dispatch = useDispatch()

  const indent = 3

  // 发送登录请求
  function onFinish(payload: SigninPayload) {
    dispatch({ type: SIGNIN, payload })
  }

  // 获取登录结果
  const {
    signin: { loaded, success, message },
  } = useSelector<AppState, AuthState>(({ auth }) => auth)

  // 显示登录结果
  function afterSignin() {
    // if (loaded) {
    const auth = isAuth()
    if (auth) {
      const {
        user: { role },
      } = auth as Auth

      return (
        <Redirect to={role === 1 ? '/admin/dashboard' : '/user/dashboard'} />
      )
    } else {
      return loaded && <Result status='error' title={message} />
    }
    // }
  }

  // 重置表单
  const [form] = Form.useForm()
  useEffect(() => {
    success && loaded && form.resetFields()
  }, [loaded, success, form])

  //
  return (
    <Layout title='登录' subTitle='注册了没？'>
      {afterSignin()}
      <Form
        form={form}
        labelCol={{
          span: indent,
        }}
        onFinish={onFinish}
      >
        <Form.Item
          label='邮箱'
          name='email'
          rules={[
            {
              required: true,
              message: 'Please input your email!',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label='密码'
          name='password'
          rules={[
            {
              required: true,
              message: 'Please input your password!',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: indent,
          }}
        >
          <Button type='primary' htmlType='submit'>
            登录
          </Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}

export default Signin
